var db = require('../models/db/db_manager');
var configure = require('../models/ballshooter');
var TABLE = require('../models/db/table');

exports.config = function (req, res, next) {
    let key = req.body.key;
    key = key || req.query.key;
    let tag = req.headers.channel;
    tag = tag || null;

    if (!key) {
        res.encryptEnd("{}");
        return;
    }

    configure(db).query(key, tag).then(function (rows) {
        if (rows.length > 0) {
            res.encryptEnd(rows[0][TABLE.ballshooter.column.value])
        } else if (tag) { // 找不到则使用默认的配置
            console.log("tag=" + tag + " not found,use default config");
            return configure(db).query(key, null).then(function (rows) {
                if (rows.length > 0) {
                    res.encryptEnd(rows[0][TABLE.ballshooter.column.value])
                } else {
                    res.encryptEnd("{}")
                }
            })
        } else {
            res.encryptEnd("{}")
        }
    }).catch(function (error) {
        console.error(error);
        res.status(500).send('Internal Server Error:' + error)
    })
};

exports.update = function (req, res, next) {
    let data = req.query.data;
    let where = req.query.where;
    if (!data) {
        return res.status(400).send('Error: data is null');
    }

    configure(db).update(data, where).then(function (result) {
        res.end(JSON.stringify(result))
    }).catch(function (error) {
        console.error(error);
        res.status(500).send('Internal Server Error:' + error)
    })
};